/**************************************************************************************************
  Filename:       zcl_NewbitTemperatureHumiditySensor.c
  Revised:        $Date: 2014-10-24 16:04:46 -0700 (Fri, 24 Oct 2014) $
  Revision:       $Revision: 40796 $

  Description:    Zigbee Cluster Library - sample device application.


  Copyright 2013 Texas Instruments Incorporated. All rights reserved.

  IMPORTANT: Your use of this Software is limited to those specific rights
  granted under the terms of a software license agreement between the user
  who downloaded the software, his/her employer (which must be your employer)
  and Texas Instruments Incorporated (the "License").  You may not use this
  Software unless you agree to abide by the terms of the License. The License
  limits your use, and you acknowledge, that the Software may not be modified,
  copied or distributed unless embedded on a Texas Instruments microcontroller
  or used solely and exclusively in conjunction with a Texas Instruments radio
  frequency transceiver, which is integrated into your product.  Other than for
  the foregoing purpose, you may not use, reproduce, copy, prepare derivative
  works of, modify, distribute, perform, display or sell this Software and/or
  its documentation for any purpose.

  YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
  PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
  NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
  TEXAS INSTRUMENTS OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER CONTRACT,
  NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
  LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
  INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
  OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
  OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
  (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.

  Should you have any questions regarding your right to use this Software,
  contact Texas Instruments Incorporated at www.TI.com.
**************************************************************************************************/

/*********************************************************************
  This application implements a ZigBee Temperature Sensor, based on Z-Stack 3.0.

  This application is based on the common sample-application user interface. Please see the main
  comment in zcl_sampleapp_ui.c. The rest of this comment describes only the content specific for
  this sample applicetion.
  
  Application-specific UI peripherals being used:

  - LEDs:
    LED1 is not used in this application

  Application-specific menu system:

    <SET LOCAL TEMP> Set the temperature of the local temperature sensor
      Up/Down changes the temperature 
      This screen shows the following information:
        Line2:
          Shows the temperature of the local temperature sensor

*********************************************************************/

/*********************************************************************
 * INCLUDES
 */
#include "ZComDef.h"
#include "OSAL.h"
#include "AF.h"
#include "ZDApp.h"
#include "ZDObject.h"
#include "ZDProfile.h"
#include "MT_SYS.h"
#include "OSAL_Clock.h"
#include "zcl.h"
#include "zcl_general.h"
#include "zcl_ha.h"
#include "zcl_ms.h"
#include "zcl_hvac.h"

#include "zcl_NewbitTemperatureHumiditySensor.h"

#include "onboard.h"

/* HAL */
#include "hal_lcd.h"
#include "hal_led.h"
#include "hal_key.h"
#include "hal_uart.h"
#include "hal_adc.h"

#include "bdb_interface.h"
#include "bdb_Reporting.h"

#if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
#include "zcl_ota.h"
#include "hal_ota.h"
#endif
#if defined ( INTER_PAN )
  #include "stub_aps.h"
#if defined ( BDB_TL_INITIATOR )
  #include "bdb_touchlink_initiator.h"
#endif // BDB_TL_INITIATOR
#if defined ( BDB_TL_TARGET )
  #include "bdb_touchlink_target.h"
#endif // BDB_TL_TARGET
#endif // INTER_PAN            
#ifdef APP_KEY
#include "AppKey.h"
#endif

#include <stdio.h>
#include <string.h>
#include "SHT21.h"
#include "hal_eflash.h"

#ifdef  NEWBIT_OLED
#include "nb_u8g2_api.h"
#endif

#ifdef HAL_DHT11
#include "hal_dht11.h"
#endif
#ifdef APP_MENU
#include "Menu.h"
#endif

#include "AddrMgr.h"
/*********************************************************************
 * MACROS
 */

// how often to report temperature
#define TEMPERATURE_HUMIDITY_SENSOR_REPORT_INTERVAL   10000


#define KEY_PRESS_TIME_3S_CNT (3000 / APP_KEY_SCAN_VALUE_MS) 


#if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
#define DEVICE_POLL_RATE                 0   // Poll rate for end device
#endif
/*********************************************************************
 * CONSTANTS
 */

/*********************************************************************
 * TYPEDEFS
 */

/*********************************************************************
 * GLOBAL VARIABLES
 */
byte zclTemperatureHumiditySensor_TaskID;

extern int16 zdpExternalStateTaskID;


/*********************************************************************
 * GLOBAL FUNCTIONS
 */

/*********************************************************************
 * LOCAL VARIABLES
 */

devStates_t Dev_NwkState = DEV_INIT;

//static uint8 aProcessCmd[] = { 1, 0, 0, 0 }; // used for reset command, { length + cmd0 + cmd1 + data }

// Test Endpoint to allow SYS_APP_MSGs

//static endPointDesc_t sampleTemperatureSensor_TestEp =
//{
//  TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,                                 // Test endpoint
//  0,
//  &zclTemperatureHumiditySensor_TaskID,
//  (SimpleDescriptionFormat_t *)NULL,  // No Simple description for this test endpoint
//  (afNetworkLatencyReq_t)0            // No Network Latency req
//};

#ifdef BDB_REPORTING
#if BDBREPORTING_MAX_ANALOG_ATTR_SIZE == 8
  uint8 reportableChange[] = {0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // 0x2C01 is 300 in int16  12C
#endif
#if BDBREPORTING_MAX_ANALOG_ATTR_SIZE == 4
  uint8 reportableChange[] = {0x2C, 0x01, 0x00, 0x00}; // 0x2C01 is 300 in int16
#endif 
#if BDBREPORTING_MAX_ANALOG_ATTR_SIZE == 2
  uint8 reportableChange[] = {0x2C, 0x01}; // 0x2C01 is 300 in int16
#endif 
#endif

BindInfoTable_t BindInfoTable = {0,{0xFFFF, 0xFF, {0xFF}}};
/*********************************************************************
 * LOCAL FUNCTIONS
 */
#if (defined APP_KEY)
static void zclTemperatureHumiditySensor_HandleKeys( keyPressCnt_t* msg );  
#else
static void zclTemperatureHumiditySensor_HandleKeys( byte shift, byte keys );
#endif
static void zclTemperatureHumiditySensor_BasicResetCB( void );

static void zclTemperatureHumiditySensor_ProcessCommissioningStatus(bdbCommissioningModeMsg_t* bdbCommissioningModeMsg);

// Functions to process ZCL Foundation incoming Command/Response messages
static void zclTemperatureHumiditySensor_ProcessIncomingMsg( zclIncomingMsg_t *msg );
#ifdef ZCL_READ
static uint8 zclTemperatureHumiditySensor_ProcessInReadRspCmd( zclIncomingMsg_t *pInMsg );
#endif
#ifdef ZCL_WRITE
static uint8 zclTemperatureHumiditySensor_ProcessInWriteRspCmd( zclIncomingMsg_t *pInMsg );
static uint8 zclTemperatureHumiditySensor_ProcessInWriteCmd( zclIncomingMsg_t *pInMsg );
#endif
#ifdef ZCL_REPORT
static uint8 zclTemperatureHumiditySensor_ProcessInReportCmd( zclIncomingMsg_t *pInMsg );
#endif
static uint8 zclTemperatureHumiditySensor_ProcessInDefaultRspCmd( zclIncomingMsg_t *pInMsg );
#ifdef ZCL_DISCOVER
static uint8 zclTemperatureHumiditySensor_ProcessInDiscCmdsRspCmd( zclIncomingMsg_t *pInMsg );
static uint8 zclTemperatureHumiditySensor_ProcessInDiscAttrsRspCmd( zclIncomingMsg_t *pInMsg );
static uint8 zclTemperatureHumiditySensor_ProcessInDiscAttrsExtRspCmd( zclIncomingMsg_t *pInMsg );
#endif // ZCL_DISCOVER

static uint8 u8BatteryPercentageRemaining(void);

void vIdentifyTimeChange(uint8 Ep);
void vBindNotification( bdbBindNotificationData_t *bindData );
void vDisplayDht11Data(HalDht11Data_t *HalDht11Data);
#if defined ( INTER_PAN )
#if defined ( BDB_TL_INITIATOR )
  ZStatus_t touchLink_NotifyAppTLCB( epInfoRec_t *pData );
#endif // BDB_TL_INITIATOR
#if defined ( BDB_TL_TARGET )

#endif // BDB_TL_TARGET
#endif // INTER_PAN

#if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
static void zclTemperatureHumiditySensor_ProcessOTAMsgs( zclOTA_CallbackMsg_t* pMsg );
#endif

void zclTemperatureHumiditySensor_ProcessZDOMsgs(zdoIncomingMsg_t *pMsg );

/*********************************************************************
 * STATUS STRINGS
 */

/*********************************************************************
 * CONSTANTS
 */


/*********************************************************************
 * ZCL General Profile Callback table
 */
static zclGeneral_AppCallbacks_t zclTemperatureHumiditySensor_CmdCallbacks =
{
  zclTemperatureHumiditySensor_BasicResetCB,      // Basic Cluster Reset command
  NULL,                                           // Identify Trigger Effect command
  NULL,             				                      // On/Off cluster command
  NULL,                                           // On/Off cluster enhanced command Off with Effect
  NULL,                                           // On/Off cluster enhanced command On with Recall Global Scene
  NULL,                                           // On/Off cluster enhanced command On with Timed Off
#ifdef ZCL_LEVEL_CTRL
  NULL,                                           // Level Control Move to Level command
  NULL,                                           // Level Control Move command
  NULL,                                           // Level Control Step command
  NULL,                                           // Level Control Stop command
#endif
#ifdef ZCL_GROUPS
  NULL,                                           // Group Response commands
#endif
#ifdef ZCL_SCENES
  NULL,                                           // Scene Store Request command
  NULL,                                           // Scene Recall Request command
  NULL,                                           // Scene Response command
#endif
#ifdef ZCL_ALARMS
  NULL,                                           // Alarm (Response) commands
#endif
#ifdef SE_UK_EXT
  NULL,                                           // Get Event Log command
  NULL,                                           // Publish Event Log command
#endif
  NULL,                                           // RSSI Location command
  NULL                                            // RSSI Location Response command
};


/*********************************************************************
 * @fn          zclTemperatureHumiditySensor_Init
 *
 * @brief       Initialization function for the zclGeneral layer.
 *
 * @param       none
 *
 * @return      none
 */
void zclTemperatureHumiditySensor_Init( byte task_id )
{
  zclTemperatureHumiditySensor_TaskID = task_id;
  
  osal_setClock(osal_ConvertUTCSecs(&utc_struct));
#ifdef  NEWBIT_OLED
   u8g2_init(U8G2_R0);
#endif
  // Register the Simple Descriptor for this application
  bdb_RegisterSimpleDescriptor( &zclTemperatureHumiditySensor_SimpleDesc ); 
  
  // Register the ZCL General Cluster Library callback functions
  zclGeneral_RegisterCmdCallbacks( TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, &zclTemperatureHumiditySensor_CmdCallbacks );

  // Register the application's attribute list
  zclTemperatureHumiditySensor_ResetAttributesToDefaultValues();
  zcl_registerAttrList( TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, zclTemperatureHumiditySensor_NumAttributes, zclTemperatureHumiditySensor_Attrs );   

  // Register the Application to receive the unprocessed Foundation command/response messages
  zcl_registerForMsg( zclTemperatureHumiditySensor_TaskID );

  // Register for all key events - This app will handle all key events
  RegisterForKeys( zclTemperatureHumiditySensor_TaskID );

  bdb_RegisterCommissioningStatusCB( zclTemperatureHumiditySensor_ProcessCommissioningStatus );

#ifdef BDB_REPORTING
  //Adds the default configuration values for the temperature attribute of the ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT cluster, for endpoint TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT
  //Default maxReportingInterval value is 10 seconds
  //Default minReportingInterval value is 3 seconds
  //Default reportChange value is 300 (3 degrees)
  bdb_RepAddAttrCfgRecordDefaultToList(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT, ATTRID_MS_TEMPERATURE_MEASURED_VALUE, 0, 300, reportableChange);
  bdb_RepAddAttrCfgRecordDefaultToList(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY, ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE, 0, 300, reportableChange);
#endif
  
  zdpExternalStateTaskID = zclTemperatureHumiditySensor_TaskID;


  
#ifdef RTR_NWK
  HalLcdWriteString( "ZR TPHP", 2 );
#else
  HalLcdWriteString( "ZED TPHP", 2 );
#endif


#if (defined HAL_UART) && (HAL_UART == TRUE)
  halUARTCfg_t uartConfig;
    /* UART Configuration */
  uartConfig.configured           = TRUE;
  uartConfig.baudRate             = HAL_UART_BR_115200;
  uartConfig.flowControl          = FALSE;
  uartConfig.flowControlThreshold = 0;
  uartConfig.rx.maxBufSize        = 128;
  uartConfig.tx.maxBufSize        = 128;
  uartConfig.idleTimeout          = 6;
  uartConfig.intEnable            = FALSE;

  uartConfig.callBackFunc         = NULL;

  
  HalUARTOpen (HAL_UART_PORT_0, &uartConfig);
  
  printf( "UART Init task_id %d!\n", task_id);


#endif //HAL_UART

#if (defined APP_KEY)
  AppKeyInit(); 
#endif
	
#if (defined HAL_ADC) && (HAL_ADC == TRUE)
  HalAdcSetReference(
                     HAL_ADC_REF_125V
                     //HAL_ADC_REF_AVDD
                       );
#endif
  
  bdb_initialize();
//  printf("IsOnANetwork: %d\n", bdbAttributes.bdbNodeIsOnANetwork);
//  if(bdbAttributes.bdbNodeIsOnANetwork == FALSE)
//  {
//     bdb_StartCommissioning(BDB_COMMISSIONING_MODE_NWK_STEERING);
//  }
  bdb_RegisterIdentifyTimeChangeCB(vIdentifyTimeChange);
  bdb_RegisterBindNotificationCB(vBindNotification);
  //vSHT21Init();
  #if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
  // Register for callback events from the ZCL OTA
  zclOTA_Register(zclTemperatureHumiditySensor_TaskID);
  
  hal_eFlashInit();
// erase whole x flash
//  halEraseeFlash();
//  halMcuWaitMs(20000);// 20s
 
  uint32 addr =0;
  uint8 buf[256];
  for(int i = 0; i < 1024; i++)
  {
     halReadeFlash(addr, &buf[0], 1);
     halMcuWaitMs(1);// 
     if(buf[0] != 0xFF)
     {
        printf("%lu = %02X\n", addr, buf[0]);
        halEraseSector(0);
         halMcuWaitMs(1000);// 
        halEraseSector(1);
         halMcuWaitMs(1000);// 
        halEraseSector(2);
         halMcuWaitMs(1000);// 
        halEraseSector(3);
        printf("halEraseSector\n");
        HalLcdWriteString("halEraseSector", 1);
        break;
     }
     addr += 256;
  }
  
//  for(int i = 0; i < 32; ++i)
//  {
//    buf[i] = (uint8)i;
//  }
//  for(uint16 page = 0; page < 8192; ++page)
//  {
//    halProgrameFlash(addr, buf, 32);
//    addr += 32;  
//  }
//  osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, 3000);

#endif
  
 #if defined ( BDB_TL_INITIATOR )
   touchLinkInitiator_RegisterNotifyTLCB( touchLink_NotifyAppTLCB );
#endif // BDB_TL_INITIATOR 
 

    
  vMenuInit();
  osal_start_timerEx( task_id,TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT,2000);
  ZDO_RegisterForZDOMsg( task_id, End_Device_Bind_rsp );
  ZDO_RegisterForZDOMsg( task_id, Match_Desc_rsp );  
  ZDO_RegisterForZDOMsg( task_id, Device_annce );  
  ZDO_RegisterForZDOMsg( task_id, Simple_Desc_rsp );    
  ZDO_RegisterForZDOMsg( task_id, Bind_rsp );
  ZDO_RegisterForZDOMsg( task_id, Unbind_rsp );
  ZDO_RegisterForZDOMsg( task_id, IEEE_addr_rsp );
  
  initBindInfoTable();
  if(u8BindInfoTableNvRead() != SUCCESS)
  {
    u8InitBindInfoTableNv();
  }
  BindRestoreFromNV();
    
}

/*********************************************************************
 * @fn          zclSample_event_loop
 *
 * @brief       Event Loop Processor for zclGeneral.
 *
 * @param       none
 *
 * @return      none
 */
uint16 zclTemperatureHumiditySensor_event_loop( uint8 task_id, uint16 events )
{
  afIncomingMSGPacket_t *MSGpkt;

  (void)task_id;  // Intentionally unreferenced parameter
#ifdef POWER_SAVING
  
#endif
  if ( events & SYS_EVENT_MSG )
  {
    while ( (MSGpkt = (afIncomingMSGPacket_t *)osal_msg_receive( zclTemperatureHumiditySensor_TaskID )) )
    {
      switch ( MSGpkt->hdr.event )
      {
        case ZCL_INCOMING_MSG:
          // Incoming ZCL Foundation command/response messages
          zclTemperatureHumiditySensor_ProcessIncomingMsg( (zclIncomingMsg_t *)MSGpkt );
          break;
        
        case KEY_CHANGE:
          
#if (defined APP_KEY)
          zclTemperatureHumiditySensor_HandleKeys((keyPressCnt_t *)MSGpkt);
#else
          zclTemperatureHumiditySensor_HandleKeys( ((keyChange_t *)MSGpkt)->state, ((keyChange_t *)MSGpkt)->keys );
#endif //APP_KEY
          break;
         case HAL_DHT11_DATA:
          
          vDisplayDht11Data((HalDht11Data_t *)MSGpkt);
          break;
          
        case ZDO_STATE_CHANGE:
          Dev_NwkState = (devStates_t)(MSGpkt->hdr.status);
          
          printf("NwkState %d\n", Dev_NwkState);
          if(Dev_NwkState ==  DEV_END_DEVICE)
          {
             vCompleteProgressBar(TRUE);
             printf("Pan %04X, F %04X, Addr %04X\n", _NIB.nwkPanId, _NIB.nwkCoordAddress, _NIB.nwkDevAddress);
        //     NwkPollReq(0);
        //     NLME_SetPollRate(0);
             
          }


          break;
#if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
        case ZCL_OTA_CALLBACK_IND:
          zclTemperatureHumiditySensor_ProcessOTAMsgs( (zclOTA_CallbackMsg_t*)MSGpkt  );
          break;
#endif
      case ZDO_CB_MSG:
        zclTemperatureHumiditySensor_ProcessZDOMsgs((zdoIncomingMsg_t *)MSGpkt );
        break;
        
        default:
          break;
      }

      // Release the memory
      osal_msg_deallocate( (uint8 *)MSGpkt );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }
  
#if ZG_BUILD_ENDDEVICE_TYPE    
  if ( events & SAMPLEAPP_END_DEVICE_REJOIN_EVT )
  {
    
    printf("bdbAttributes.bdbNodeIsOnANetwork: %d\n", bdbAttributes.bdbNodeIsOnANetwork);
    printf("bdbCommissioningProcedureState.bdbCommissioningState: %d\n", bdbCommissioningProcedureState.bdbCommissioningState);
     
    uint8 u8Status = bdb_ZedAttemptRecoverNwk(); 
    
    printf("AttemptRecoverNwk Status: %d\n", u8Status);
    return ( events ^ SAMPLEAPP_END_DEVICE_REJOIN_EVT );
  }
#endif
 
  if ( events & TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT )
  {
//   static uint16 readaddr = 0;
//   uint8 readbuf =0;
//   halReadeFlash(readaddr, &readbuf, 1);
//   printf("buf = %d, addr = %u\n", readbuf, readaddr++);
//   osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, 5);
//  printf("V = %d\n",u8BatteryPercentageRemaining());
//  
//   if(flag )
//    {
//      flag = 1;
//      //u8SHT21SetOrReadRes(SHT21_RES_RH_8_T_12);
//      
//      //bSHT21WriteCmd(SHT21_HUMI_CMD_NO_HOST_MASTER);
//     
//      //bSHT21WriteCmd(SHT21_TEMP_CMD_NO_HOST_MASTER);
//      bSHT21WriteCmd(SHT21_TEMP_CMD_HOST_MASTER);
//      
//      //osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, 3000);
//    }
//    else
//    {
//      flag= 0;
//      
//      //HalLedBlink(HAL_LED_2,5, 50 ,100 );
//      //temp = u16SHT21ReadHumiOrTemp();
//      
//      temp = fSHT21HostMasterReadHumiOrTemp();
//      printf("V = %d\n",u8BatteryPercentageRemaining());
//       //HalLedSet(HAL_LED_2, HAL_LED_MODE_OFF);
//      //osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, 3000);
//      printf("temp = %f\n", temp);
//      //zclTemperatureSensor_MeasuredValue = (uint16) (temp * 100);  // considering using whole number value
//      //HalLcdWriteStringValue("TEM Data ", zclTemperatureSensor_MeasuredValue, 10, 3);
////               vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
////                                  TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
////                                  ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT,
////                                  ATTRID_MS_TEMPERATURE_MEASURED_VALUE);
////     vReportClusterWithReportFlag(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
////                                           TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
////                                           ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT);
//
//    }
    vHalDht11Start();        
    osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_DELAY);
    return ( events ^ TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT );
  }
   
  if ( events & TEMPERATURE_HUMIDITY_SENSOR_TL_EVT )
  {
     bdb_StartCommissioning(BDB_COMMISSIONING_MODE_INITIATOR_TL);
               
    return ( events ^ TEMPERATURE_HUMIDITY_SENSOR_TL_EVT );
  }

  if ( events & MATCH_BIND_EVT )
  {
    if(checkBindInfoIsNull())
    {
      extern void vKeyEnterBind(void);
      vCompleteProgressBar(TRUE);
      setMatchInfo();
      vKeyEnterBind();
    }
    else
      vCompleteProgressBar(FALSE);
    
    return ( events ^ MATCH_BIND_EVT );
  }
  if ( events & DISPLAY_PROGRESS_BAR_EVT )
  {
    
    vProgressBarCheckTimeout();
    
    return ( events ^ DISPLAY_PROGRESS_BAR_EVT );
  }
  // Discard unknown events
  return 0;
}

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_HandleKeys
 *
 * @brief   Handles all key events for this device.
 *
 * @param   shift - true if in shift/alt.
 * @param   keys - bit field for key events. Valid entries:
 *                 HAL_KEY_SW_5
 *                 HAL_KEY_SW_4
 *                 HAL_KEY_SW_3
 *                 HAL_KEY_SW_2
 *                 HAL_KEY_SW_1
 *
 * @return  none
 */
#if (defined APP_KEY)
static void zclTemperatureHumiditySensor_HandleKeys( keyPressCnt_t* msg )
{
#ifdef LCD_SUPPORTED					 
  char i8Buff[16]={' '};
 sprintf(i8Buff, "KeyT %d %d %04x \n",msg->keyPressCnt.u8TimeCnt , msg->keyPressCnt.bKeyState, (uint16)msg->keyPressCnt.u32KeyGPIO);
 HalLcdWriteString( i8Buff, 4 );
#endif	
 afAddrType_t afAddrType_DstAddr;
   //按键已松开
   if(msg->keyPressCnt.bKeyState == APP_KEY_RELEASE)
   {
      //printf("Release %d ms IO:%lX\n", msg->keyPressCnt.u8TimeCnt*APP_KEY_SCAN_VALUE_MS, msg->keyPressCnt.u32KeyGPIO);
      switch(msg->keyPressCnt.u32KeyGPIO)
      {
        case APP_KEY_0:
          if(msg->keyPressCnt.u8TimeCnt < 5)//100*20 ==2000ms
          {
//             printf("BDB_COMMISSIONING_MODE_NWK_STEERING");
//             bdb_StartCommissioning(BDB_COMMISSIONING_MODE_NWK_STEERING);

//              zclHumiditySensor_MeasuredValue =(uint16 ) (zclHumiditySensor_MeasuredValue + 100);
//              HalLcdWriteStringValue("HUM Data ", zclHumiditySensor_MeasuredValue, 10, 3);
//
//              vReportClusterWithReportFlag(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
//                                           TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
//                                           ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY);
              
//               osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT, 500);
//               HalLedBlink(HAL_LED_ALL, 3, 50, 300);
         
                // Set destination address to indirect
                afAddrType_DstAddr.addrMode = (afAddrMode_t)Addr16Bit;
                afAddrType_DstAddr.endPoint = TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT;
                afAddrType_DstAddr.addr.shortAddr = _NIB.nwkCoordAddress;
                zclGeneral_SendOnOff_CmdToggle( TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, &afAddrType_DstAddr, FALSE, bdb_getZCLFrameCounter() );
     
          }      
          else
          {}
          break;
        case APP_KEY_1:
          
          if(msg->keyPressCnt.u8TimeCnt < 5)//100*20 ==2000ms
          {
            
               zclHumiditySensor_MeasuredValue = zclHumiditySensor_MeasuredValue + 100;
               HalLcdWriteStringValue("HUM Data ", zclHumiditySensor_MeasuredValue, 10, 3);
//               vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
//                                  TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
//                                  ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY, 
//                                  ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE);
               vReportClusterWithReportFlag(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
                                  TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                                  ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY);
           
          }  
          break;
         case APP_KEY_2:
          
          if(msg->keyPressCnt.u8TimeCnt < 5)//100*20 ==2000ms
          {
          
               zclTemperatureSensor_MeasuredValue = zclTemperatureSensor_MeasuredValue + 100;  // considering using whole number value
               HalLcdWriteStringValue("TEM Data ", zclTemperatureSensor_MeasuredValue, 10, 3);
//               vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
//                                  TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
//                                  ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT,
//                                  ATTRID_MS_TEMPERATURE_MEASURED_VALUE);
              vReportClusterWithReportFlag(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
                                           TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                                           ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT);
          }  
          break;
        case APP_KEY_3:
          
             printf("FINDING_BINDING\n");
             bdb_SetIdentifyActiveEndpoint(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT);
             bdb_StartCommissioning(BDB_COMMISSIONING_MODE_FINDING_BINDING);
          break;
          
        case APP_KEY_4:
          
          printf("APP_KEY_4\n");
          zclHumiditySensor_MeasuredValue = zclHumiditySensor_MeasuredValue + 400;
          bdb_RepChangedAttrValue(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
                                  ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY, 
                                  ATTRID_MS_RELATIVE_HUMIDITY_MEASURED_VALUE);
          zclTemperatureSensor_MeasuredValue = zclTemperatureSensor_MeasuredValue + 400; 
          bdb_RepChangedAttrValue(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                                  ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT, 
                                  ATTRID_MS_TEMPERATURE_MEASURED_VALUE);
          
//          bdb_RepReportCluster(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
//                               ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT);
          break;
          
        case APP_KEY_5:
          
          
          break;
          
        default:
          break;
      }
 
   }
   else//按键还没松开
   {
     //printf("Pessing %d ms, IO:%lX\n", msg->keyPressCnt.u8TimeCnt*APP_KEY_SCAN_VALUE_MS, msg->keyPressCnt.u32KeyGPIO);
      switch(msg->keyPressCnt.u32KeyGPIO)
      {
        case APP_KEY_0:
 
          if(msg->keyPressCnt.u8TimeCnt == 5)//100*20 ==2000ms
          {
               printf("bdb_resetLocalAction\n");
               HalLcdWriteString("BDB_RST!!", 3);
               bdb_resetLocalAction();
          }

          break;
        case APP_KEY_1:
          
          break;
          
        case APP_KEY_2:
          
          break;
          
        case APP_KEY_3:
          
          break;
          
        case APP_KEY_4:
          
          break;
          
        case APP_KEY_5:
          bdb_StartCommissioning(0);
          HalLcdWriteString("BDB_TL 3s!!", 3);
          osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TL_EVT, 3000);
          break;
          
        default:
          break;

      }
   }
  
}
#else
static void zclTemperatureHumiditySensor_HandleKeys( byte shift, byte keys )
{

    osal_stop_timerEx(zclTemperatureHumiditySensor_TaskID, TEMPERATURE_HUMIDITY_SENSOR_TEMP_SEND_EVT);
    if ( keys & HAL_KEY_SW_0 )
    {
      vKeyScan(KEY_ENTER);
    }
    if ( keys & HAL_KEY_SW_1 )
    {
     
      vKeyScan(KEY_LEFT);   
    }
    if ( keys & HAL_KEY_SW_2 )
    {
      
      vKeyScan(KEY_RIGHT);
    }

}
#endif
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessCommissioningStatus
 *
 * @brief   Called to display the main screen on the LCD.
 *
 * @param   none
 *
 * @return  none
 */
static void zclTemperatureHumiditySensor_ProcessCommissioningStatus(bdbCommissioningModeMsg_t* bdbCommissioningModeMsg)
{
    printf("Bmode %d status %d\n",bdbCommissioningModeMsg->bdbCommissioningMode , bdbCommissioningModeMsg->bdbCommissioningStatus);

    switch(bdbCommissioningModeMsg->bdbCommissioningMode)
    {
      case BDB_COMMISSIONING_FORMATION:
        if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
        {
          //After formation, perform nwk steering again plus the remaining commissioning modes that has not been process yet
          bdb_StartCommissioning(BDB_COMMISSIONING_MODE_NWK_STEERING | bdbCommissioningModeMsg->bdbRemainingCommissioningModes);
        }
        else
        {
          //Want to try other channels?
          //try with bdb_setChannelAttribute
        }
      break;
      case BDB_COMMISSIONING_NWK_STEERING:
        if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
        {
          //YOUR JOB:
          //We are on the nwk, what now?
          #ifdef LCD_SUPPORTED
           HalLcdWriteString("on the nwk", 1 );
          // bdb_StartCommissioning(BDB_COMMISSIONING_MODE_FINDING_BINDING | bdbCommissioningModeMsg->bdbRemainingCommissioningModes);
          #endif
          #if (defined HAL_UART) && (HAL_UART == TRUE)
           printf("We are on the nwk!\n");
          #endif
           
//          vReportCluster( TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
//                          TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
//                          ZCL_CLUSTER_ID_GEN_BASIC);

           vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       ZCL_CLUSTER_ID_GEN_BASIC,
                       ATTRID_BASIC_MODEL_ID);
           vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       ZCL_CLUSTER_ID_GEN_BASIC,
                       ATTRID_BASIC_APPL_VERSION);
           vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
                       ZCL_CLUSTER_ID_GEN_BASIC,
                       ATTRID_XIAOMI_IDENTIFICATION);
        }
        else
        {  
           //vCompleteProgressBar(FALSE);
           printf("No suitable networks found!\n");
           
           //See the possible errors for nwk steering procedure
           //No suitable networks found
           //Want to try other channels?
           //try with bdb_setChannelAttribute
        }

      break;
      case BDB_COMMISSIONING_FINDING_BINDING:
        if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
        {
          //YOUR JOB:
                printf("FB_S\n");
                bdb_StopInitiatorFindingBinding();
        }
        else
        {
          //YOUR JOB:
          //retry?, wait for user interaction?
          //printf(bdbCommissioningModeMsg->bdbCommissioningStatus);
        }
      break;
      case BDB_COMMISSIONING_INITIALIZATION:
        //Initialization notification can only be successful. Failure on initialization 
        //only happens for ZED and is notified as BDB_COMMISSIONING_PARENT_LOST notification
        
        //YOUR JOB:
        //We are on a network, what now?
        
      break;
     case BDB_COMMISSIONING_TOUCHLINK:
    
     if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_SUCCESS)
      {
        //YOUR JOB:
        printf("TOUCHLINK SUCCESS\n");
      }
      else
      {
        //YOUR JOB:
        //retry?, wait for user interaction?
        printf("TOUCHLINK FAIL\n");
      }
     
    break;
      
#if ZG_BUILD_ENDDEVICE_TYPE    
    case BDB_COMMISSIONING_PARENT_LOST:
      if(bdbCommissioningModeMsg->bdbCommissioningStatus == BDB_COMMISSIONING_NETWORK_RESTORED)
      {
        //We did recover from losing parent
      }
      else
      {
        printf("P not found, Nwk %d\n", Dev_NwkState);
        //Parent not found, attempt to rejoin again after a fixed delay
        osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, SAMPLEAPP_END_DEVICE_REJOIN_EVT, SAMPLEAPP_END_DEVICE_REJOIN_DELAY);
      }
    break;
   
#endif 
    }
  
}

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_BasicResetCB
 *
 * @brief   Callback from the ZCL General Cluster Library
 *          to set all the Basic Cluster attributes to default values.
 *
 * @param   none
 *
 * @return  none
 */
static void zclTemperatureHumiditySensor_BasicResetCB( void )
{
  zclTemperatureHumiditySensor_ResetAttributesToDefaultValues(); 
}

/******************************************************************************
 *
 *  Functions for processing ZCL Foundation incoming Command/Response messages
 *
 *****************************************************************************/

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessIncomingMsg
 *
 * @brief   Process ZCL Foundation incoming message
 *
 * @param   pInMsg - pointer to the received message
 *
 * @return  none
 */
static void zclTemperatureHumiditySensor_ProcessIncomingMsg( zclIncomingMsg_t *pInMsg)
{
#ifdef LCD_SUPPORTED
						 
 char i8Buff[16];

 sprintf(i8Buff, "ID %d Id %04x", pInMsg->zclHdr.commandID , pInMsg->clusterId);
 HalLcdWriteString( i8Buff, 2 );
#endif
 
  switch ( pInMsg->zclHdr.commandID )
  {
#ifdef ZCL_READ
    case ZCL_CMD_READ_RSP:
      zclTemperatureHumiditySensor_ProcessInReadRspCmd( pInMsg );
      break;
#endif
#ifdef ZCL_WRITE
    case ZCL_CMD_WRITE_RSP:
      zclTemperatureHumiditySensor_ProcessInWriteRspCmd( pInMsg );
      break;
      
    case ZCL_CMD_WRITE:
      zclTemperatureHumiditySensor_ProcessInWriteCmd( pInMsg );
      break;
      
#endif
#ifdef ZCL_REPORT
    // See ZCL Test Applicaiton (zcl_testapp.c) for sample code on Attribute Reporting
    case ZCL_CMD_CONFIG_REPORT:
      //zclTemperatureHumiditySensor_ProcessInConfigReportCmd( pInMsg );
      break;
      case ZCL_CMD_READ_REPORT_CFG:
      //zclTemperatureHumiditySensor_ProcessInReadReportCfgCmd( pInMsg );
      break;
    case ZCL_CMD_CONFIG_REPORT_RSP:
      //zclTemperatureHumiditySensor_ProcessInConfigReportRspCmd( pInMsg );
      break;
    case ZCL_CMD_READ_REPORT_CFG_RSP:
      //zclTemperatureHumiditySensor_ProcessInReadReportCfgRspCmd( pInMsg );
      break;

    case ZCL_CMD_REPORT:
      zclTemperatureHumiditySensor_ProcessInReportCmd( pInMsg );
      break;
#endif
    case ZCL_CMD_DEFAULT_RSP:
      zclTemperatureHumiditySensor_ProcessInDefaultRspCmd( pInMsg );
      break;
#ifdef ZCL_DISCOVER
    case ZCL_CMD_DISCOVER_CMDS_RECEIVED_RSP:
      zclTemperatureHumiditySensor_ProcessInDiscCmdsRspCmd( pInMsg );
      break;

    case ZCL_CMD_DISCOVER_CMDS_GEN_RSP:
      zclTemperatureHumiditySensor_ProcessInDiscCmdsRspCmd( pInMsg );
      break;

    case ZCL_CMD_DISCOVER_ATTRS_RSP:
      zclTemperatureHumiditySensor_ProcessInDiscAttrsRspCmd( pInMsg );
      break;

    case ZCL_CMD_DISCOVER_ATTRS_EXT_RSP:
      zclTemperatureHumiditySensor_ProcessInDiscAttrsExtRspCmd( pInMsg );
      break;
#endif
    default:
      break;
  }

  if ( pInMsg->attrCmd )
  {
    osal_mem_free( pInMsg->attrCmd );
  }
}

#ifdef ZCL_READ
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInReadRspCmd
 *
 * @brief   Process the "Profile" Read Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInReadRspCmd( zclIncomingMsg_t *pInMsg )
{
  zclReadRspCmd_t *readRspCmd;
  uint8 i;

  readRspCmd = (zclReadRspCmd_t *)pInMsg->attrCmd;
  for ( i = 0; i < readRspCmd->numAttr; i++ )
  {
    // Notify the originator of the results of the original read attributes
    // attempt and, for each successfull request, the value of the requested
    // attribute
  }

  return ( TRUE );
}
#endif // ZCL_READ

#ifdef ZCL_WRITE
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInWriteRspCmd
 *
 * @brief   Process the "Profile" Write Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInWriteRspCmd( zclIncomingMsg_t *pInMsg )
{
  zclWriteRspCmd_t *writeRspCmd;
  uint8 i;

  writeRspCmd = (zclWriteRspCmd_t *)pInMsg->attrCmd;
  for ( i = 0; i < writeRspCmd->numAttr; i++ )
  {
    // Notify the device of the results of the its original write attributes
    // command.
    printf("Attr %04x, Status %d\n", writeRspCmd->attrList[i].attrID, writeRspCmd->attrList[i].status);
  }

  return ( TRUE );
}

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInWriteCmd
 *
 * @brief   Process the "Profile" Write Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInWriteCmd( zclIncomingMsg_t *pInMsg )
{
  zclWriteCmd_t *writeCmd;
  uint8 i;

  writeCmd = (zclWriteCmd_t *)pInMsg->attrCmd;
  for ( i = 0; i < writeCmd->numAttr; i++ )
  {
    // Notify the device of the results of the its original write attributes
    // command.
  }

  return ( TRUE );
}
#endif // ZCL_WRITE

#ifdef ZCL_REPORT
static uint8 zclTemperatureHumiditySensor_ProcessInReportCmd( zclIncomingMsg_t *pInMsg )
{
  zclReportCmd_t *zclReportCmd = (zclReportCmd_t *)pInMsg->attrCmd;
  uint8 i;

  
  for ( i = 0; i < zclReportCmd->numAttr; i++ )
  {
    
  }
  
  
  return (TRUE);

}
#endif // ZCL_REPORT
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInDefaultRspCmd
 *
 * @brief   Process the "Profile" Default Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInDefaultRspCmd( zclIncomingMsg_t *pInMsg )
{
  // zclDefaultRspCmd_t *defaultRspCmd = (zclDefaultRspCmd_t *)pInMsg->attrCmd;

  // Device is notified of the Default Response command.
  (void)pInMsg;

  return ( TRUE );
}

#ifdef ZCL_DISCOVER
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInDiscCmdsRspCmd
 *
 * @brief   Process the Discover Commands Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInDiscCmdsRspCmd( zclIncomingMsg_t *pInMsg )
{
  zclDiscoverCmdsCmdRsp_t *discoverRspCmd;
  uint8 i;

  discoverRspCmd = (zclDiscoverCmdsCmdRsp_t *)pInMsg->attrCmd;
  for ( i = 0; i < discoverRspCmd->numCmd; i++ )
  {
    // Device is notified of the result of its attribute discovery command.
  }

  return ( TRUE );
}

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInDiscAttrsRspCmd
 *
 * @brief   Process the "Profile" Discover Attributes Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInDiscAttrsRspCmd( zclIncomingMsg_t *pInMsg )
{
  zclDiscoverAttrsRspCmd_t *discoverRspCmd;
  uint8 i;

  discoverRspCmd = (zclDiscoverAttrsRspCmd_t *)pInMsg->attrCmd;
  for ( i = 0; i < discoverRspCmd->numAttr; i++ )
  {
    // Device is notified of the result of its attribute discovery command.
  }

  return ( TRUE );
}

/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessInDiscAttrsExtRspCmd
 *
 * @brief   Process the "Profile" Discover Attributes Extended Response Command
 *
 * @param   pInMsg - incoming message to process
 *
 * @return  none
 */
static uint8 zclTemperatureHumiditySensor_ProcessInDiscAttrsExtRspCmd( zclIncomingMsg_t *pInMsg )
{
  zclDiscoverAttrsExtRsp_t *discoverRspCmd;
  uint8 i;

  discoverRspCmd = (zclDiscoverAttrsExtRsp_t *)pInMsg->attrCmd;
  for ( i = 0; i < discoverRspCmd->numAttr; i++ )
  {
    // Device is notified of the result of its attribute discovery command.
  }

  return ( TRUE );
}
#endif // ZCL_DISCOVER


//重写putchar函数
__near_func int putchar(int c)
{
#if (defined HAL_UART) && (HAL_UART == TRUE)
    HalUARTWrite(HAL_UART_PORT_0, (uint8 *)&c, 1);
#endif
    return c;
}

static uint8 u8BatteryPercentageRemaining(void)
{
  float Percent = 0;
  uint8 u8PercentBuff[10];
  uint8 i = 0;
  uint16 AdcVal=0;
  
  //TPHP 模块电压经分压后最大为
  //3.3 --- 0.63V
  //2.6 --- 0.50V
  for(i = 0 ; i < 5; i++)
  {
     AdcVal = HalAdcRead(HAL_ADC_CHN_AIN7, HAL_ADC_RESOLUTION_14);
     printf("AdcVal = %d, i= %d\n", AdcVal, i);
     Percent = (uint16)(AdcVal/2047.0f * 200.0f);
       
     u8PercentBuff[i] = (uint8)((Percent > 200)?200:Percent);
    
  }
  
  Percent = 0;
  for(i =0; i < 10; i++)
  {
     Percent += u8PercentBuff[i]; 
  }
  Percent = (Percent/10.0f);
  
  return ((uint8)Percent);
}

void AppPrintf( char *title, unsigned long l, unsigned char radix)
{
#if (defined HAL_UART) && (HAL_UART == TRUE) 
     
   if(radix == 0)
   {
      HalUARTWrite(HAL_UART_PORT_0, (uint8 *)title, osal_strlen(title));
      HalUARTWrite(HAL_UART_PORT_0, "\n", osal_strlen("\n"));
      return;
   }
   int len = osal_strlen(title);
   uint8 *u8string = osal_mem_alloc(len + 10);
   if( NULL == u8string)
    return ;
   
   osal_memcpy(&u8string, title, len);
   if(radix == 16)
   {
       osal_memcpy(&u8string[len], "0x", 2);
       _ltoa(l, &u8string[len+2], radix);
   }
   else
   {
       _ltoa(l, &u8string[len], radix);
   }
   
   HalUARTWrite(HAL_UART_PORT_0, (uint8 *)u8string, osal_strlen((char *)u8string));
   HalUARTWrite(HAL_UART_PORT_0, "\n", osal_strlen("\n"));
   osal_mem_free(u8string);
  
#else
  (void)title;
  (void)l;
  (void)radix;
#endif
}
void vIdentifyTimeChange(uint8 Ep)
{
  HalLcdWriteStringValue("ITC:", Ep, 10, 2);
  AppPrintf("ITC:", Ep, 10);
}

void vBindNotification( bdbBindNotificationData_t *bindData )
{
  HalLcdWriteStringValueValue("BN:", bindData->clusterId, 16, bindData->ep, 10, 3);
  printf("BN: %04X, %d\n", bindData->clusterId, bindData->ep);
  bdb_StopInitiatorFindingBinding();
}
uint8 u8AttrCnt(uint16 u16Cluster)
{
  uint8 i  =0, u8Cnt =0;
  
  for(i =0; i < zclTemperatureHumiditySensor_NumAttributes; i++)
  {
    if(zclTemperatureHumiditySensor_Attrs[i].clusterID == u16Cluster)
      u8Cnt++;
  }
  return u8Cnt;
}
  
/*******************************************************************************  
 * Function:   vReportClusterWithReportFlag
 * Description:   Report all attrs whith ACCESS_REPORTABLE of cluster 
 * Input parameter:    uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/  
void vReportClusterWithReportFlag( uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster)
{
    uint8 u8ClusterAttrs = 0 ;
    uint8 x=0 ,y=0;
    zclAttrRecsList *pRec = zclFindAttrRecsList( u8SrcEp );
    zclReportCmd_t *pReportCmd;
    afAddrType_t dstAddr;
     
    for( x = 0; x < pRec->numAttributes; x++)
    {
      if((pRec->attrs[x].clusterID == u16Cluster) && (pRec->attrs[x].attr.accessControl & ACCESS_REPORTABLE))
      {  
        u8ClusterAttrs++;
      }
    }
    
    pReportCmd = osal_mem_alloc( sizeof( zclReportCmd_t ) + (u8ClusterAttrs * sizeof( zclReport_t )) );
    pReportCmd->numAttr = u8ClusterAttrs;
    
    if ( (pRec != NULL) && (pReportCmd != NULL))
    {
      for ( x = 0; x < u8ClusterAttrs; x++ )
      {
         for( ; y < pRec->numAttributes; y++)
         {
            if((pRec->attrs[y].clusterID) == u16Cluster && (pRec->attrs[y].attr.accessControl & ACCESS_REPORTABLE))
            {  
              pReportCmd->attrList[x].attrID = pRec->attrs[y].attr.attrId;
              pReportCmd->attrList[x].dataType = pRec->attrs[y].attr.dataType;
              pReportCmd->attrList[x].attrData = (uint8 *)pRec->attrs[y].attr.dataPtr;
              y++;
              break;
            }
         }
      }
     
     dstAddr.addrMode = (afAddrMode_t)Addr16Bit;
     dstAddr.addr.shortAddr = 0x0000;
     dstAddr.endPoint = u8DstEp;
     dstAddr.panId = _NIB.nwkPanId;

     zcl_SendReportCmd(u8SrcEp, &dstAddr,u16Cluster, pReportCmd,
                       ZCL_FRAME_SERVER_CLIENT_DIR, FALSE, bdb_getZCLFrameCounter());

   
    } 
    if ( pReportCmd != NULL)
      osal_mem_free(pReportCmd);
}
/*******************************************************************************  
 * Function:   vReportCluster
 * Description:   Report all attrs of cluster 
 * Input parameter:    uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void vReportCluster( uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster)
{
    uint8 u8ClusterAttrs = 0 ;
    uint8 x=0 ,y=0;
    zclAttrRecsList *pRec = zclFindAttrRecsList( u8SrcEp );
    zclReportCmd_t *pReportCmd;
    afAddrType_t dstAddr;
     
    for( x = 0; x < pRec->numAttributes; x++)
    {
      if(pRec->attrs[x].clusterID == u16Cluster)
      {  
        u8ClusterAttrs++;
      }
    }
    
    pReportCmd = osal_mem_alloc( sizeof( zclReportCmd_t ) + (u8ClusterAttrs * sizeof( zclReport_t )) );
    pReportCmd->numAttr = u8ClusterAttrs;
    
    if ( (pRec != NULL) && (pReportCmd != NULL))
    {
      for ( x = 0; x < u8ClusterAttrs; x++ )
      {
         for( ; y < pRec->numAttributes; y++)
         {
            if(pRec->attrs[y].clusterID == u16Cluster)
            {  
              pReportCmd->attrList[x].attrID = pRec->attrs[y].attr.attrId;
              pReportCmd->attrList[x].dataType = pRec->attrs[y].attr.dataType;
              pReportCmd->attrList[x].attrData = (uint8 *)pRec->attrs[y].attr.dataPtr;
              y++;
              break;
            }
         }
      }
     
     dstAddr.addrMode = (afAddrMode_t)Addr16Bit;
     dstAddr.addr.shortAddr = 0x0000;
     dstAddr.endPoint = u8DstEp;
     dstAddr.panId = _NIB.nwkPanId;

     zcl_SendReportCmd(u8SrcEp, &dstAddr,u16Cluster, pReportCmd,
                       ZCL_FRAME_SERVER_CLIENT_DIR, FALSE, bdb_getZCLFrameCounter());

     
    } 
    if ( pReportCmd != NULL)
      osal_mem_free(pReportCmd);
}
  
/*******************************************************************************  
 * Function:   vReportAtrr
 * Description:   Report a attribute  of cluster 
 * Input parameter:   uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster, uint16 u16Attr
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void vReportAtrr( uint8 u8SrcEp, uint8 u8DstEp, uint16 u16Cluster, uint16 u16Attr)
{
    uint8 y=0;
    zclAttrRecsList *pRec = zclFindAttrRecsList( u8SrcEp );
    zclReportCmd_t *pReportCmd;
    afAddrType_t dstAddr;
    //ZStatus_t ZStatus;
       
    pReportCmd = osal_mem_alloc( sizeof( zclReportCmd_t ) + (1 * sizeof( zclReport_t )) );
    pReportCmd->numAttr = 1;
    pReportCmd->attrList[0].attrID = u16Attr;
    
    if ( (pRec != NULL) && (pReportCmd != NULL))
    {
         for( y = 0; y < pRec->numAttributes; y++)
         {
            if((pRec->attrs[y].clusterID == u16Cluster) && (pRec->attrs[y].attr.attrId == u16Attr))
            {  
              pReportCmd->attrList[0].dataType = pRec->attrs[y].attr.dataType;
              pReportCmd->attrList[0].attrData = (uint8 *)pRec->attrs[y].attr.dataPtr;
              break;
            }
         }
     
     dstAddr.addrMode = (afAddrMode_t)Addr16Bit;
     dstAddr.addr.shortAddr = 0x0000;
     dstAddr.endPoint = u8DstEp;
     dstAddr.panId = _NIB.nwkPanId;

     //ZStatus = 
       zcl_SendReportCmd(u8SrcEp, &dstAddr,u16Cluster, pReportCmd,
                       ZCL_FRAME_SERVER_CLIENT_DIR, TRUE, bdb_getZCLFrameCounter());
     
     //printf("Report s 0x%x\n", ZStatus);
     
    } 
    if ( pReportCmd != NULL)
      osal_mem_free(pReportCmd);
}


#if defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)
/*********************************************************************
 * @fn      zclTemperatureHumiditySensor_ProcessOTAMsgs
 *
 * @brief   Called to process callbacks from the ZCL OTA.
 *
 * @param   none
 *
 * @return  none
 */
static void zclTemperatureHumiditySensor_ProcessOTAMsgs( zclOTA_CallbackMsg_t* pMsg )
{
  uint8 RxOnIdle;

  switch(pMsg->ota_event)
  {
  case ZCL_OTA_START_CALLBACK:
    if (pMsg->hdr.status == ZSuccess)
    {
      // Speed up the poll rate
      RxOnIdle = TRUE;
      ZMacSetReq( ZMacRxOnIdle, &RxOnIdle );
      NLME_SetPollRate( 1000 );
      
      HalLcdWriteString("OTA_START_CB", 4);
    }
    break;

  case ZCL_OTA_DL_COMPLETE_CALLBACK:
    if (pMsg->hdr.status == ZSuccess)
    {
      HalLcdWriteString("OTA_DL_COMPLETE", 4);
      // Reset the CRC Shadow and reboot.  The bootloader will see the
      // CRC shadow has been cleared and switch to the new image
      HalOTAInvRC();
      SystemReset();
    }
    else
    {
      // slow the poll rate back down.
      RxOnIdle = FALSE;
      ZMacSetReq( ZMacRxOnIdle, &RxOnIdle );
      NLME_SetPollRate(DEVICE_POLL_RATE);
    }
    break;

  default:
    break;
  }
}
#endif // defined (OTA_CLIENT) && (OTA_CLIENT == TRUE)

#if defined ( INTER_PAN )
#if defined ( BDB_TL_INITIATOR )
ZStatus_t touchLink_NotifyAppTLCB( epInfoRec_t *pData )
{
  printf("dID %04X, Ep %d, Addr %04X, pID %04X, Ver %04X", pData->deviceID, pData->endpoint, pData->nwkAddr, pData->profileID, pData->version);
  return 0;
}
#endif // BDB_TL_INITIATOR
#if defined ( BDB_TL_TARGET )

#endif // BDB_TL_TARGET
#endif // INTER_PAN


//width:128,height:32
//const unsigned char col[] U8X8_PROGMEM= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xe0,0x7f,0xf8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xc0,0x7f,0xf8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xc0,0x7f,0xf8,0x81,0xff,0xe7,0x03,0x3e,0xe0,0xf3,0xff,0x80,0xc7,0xff,0x3f,0xfc,0x80,0x7f,0xf8,0x81,0xff,0xe7,0x03,0x7e,0xe0,0xf1,0xff,0x81,0xc7,0xff,0x3f,0xfc,0x80,0x7f,0xf8,0x81,0xff,0xc7,0x07,0x7e,0xe0,0xf1,0xff,0x83,0xc7,0xff,0x3f,0xfc,0x00,0x7f,0xf8,0x81,0xef,0xc3,0x07,0x7f,0xf0,0xf1,0xe1,0x87,0x87,0xfb,0x3d,0xfc,0x00,0x7e,0xf8,0x81,0x07,0xc0,0x07,0x7f,0xf0,0xf1,0xc1,0x87,0x07,0xf0,0x00,0xfc,0x00,0x7e,0xf8,0x81,0x0f,0xc0,0x07,0xff,0xf0,0xf0,0xc1,0x87,0x07,0xf0,0x00,0xfc,0x10,0x7e,0xf8,0x81,0x0f,0x80,0x87,0xff,0xf0,0xf0,0xc1,0x83,0x07,0xf0,0x00,0xfc,0x30,0x7f,0xf8,0x81,0x0f,0x80,0x8f,0xf7,0xf8,0xf0,0xe1,0x83,0x07,0xf0,0x00,0xfc,0xf0,0x78,0xf8,0x81,0xff,0x83,0x8f,0xf7,0x78,0xf0,0xff,0x80,0x07,0xf0,0x00,0xfc,0x70,0x70,0xf8,0x81,0xff,0x83,0x8f,0xf7,0x79,0xf0,0xff,0x80,0x07,0xf0,0x00,0xfc,0x70,0x70,0xf8,0x81,0xff,0x03,0xcf,0xe3,0x79,0xf0,0xff,0x83,0x07,0xf0,0x00,0xfc,0xf0,0x78,0xf8,0x81,0xff,0x03,0xcf,0xe3,0x79,0xf0,0xfd,0x87,0x07,0xf0,0x00,0xfc,0xf0,0x67,0xf8,0x81,0x0f,0x00,0xdf,0xe3,0x39,0xf0,0xc1,0x87,0x07,0xf0,0x00,0xfc,0xf0,0x43,0xf8,0x81,0x0f,0x00,0xde,0xe1,0x3d,0xf0,0x81,0x8f,0x07,0xf0,0x00,0xfc,0xf0,0x03,0xf8,0x81,0x0f,0x00,0xfe,0xc1,0x3f,0xf0,0x81,0x8f,0x07,0xf0,0x00,0xfc,0xf0,0x07,0xf8,0x81,0x07,0x00,0xfe,0xc1,0x3f,0xf0,0xc1,0x87,0x07,0xf0,0x00,0xfc,0xf0,0x07,0xf8,0x81,0x0f,0x00,0xfe,0xc1,0x1f,0xf0,0xe1,0x87,0x07,0xf0,0x00,0xfc,0xf0,0x0f,0xf8,0x81,0xff,0x07,0xfc,0xc0,0x1f,0xf0,0xff,0x87,0x07,0xf0,0x00,0xfc,0xf0,0x0f,0xf8,0x81,0xff,0x07,0xfc,0x80,0x1f,0xf0,0xff,0x83,0x07,0xf0,0x00,0xfc,0xf0,0x1f,0xf8,0x81,0xff,0x07,0xfc,0x80,0x1f,0xf0,0xff,0x80,0x07,0xf0,0x00,0xfc,0xf0,0x3f,0xf8,0x01,0x00,0x04,0x48,0x00,0x09,0x20,0x00,0x00,0x04,0x80,0x00,0xfc,0xf0,0x3f,0xf8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; 

//width:117,height:64
//const unsigned char col[] U8X8_PROGMEM = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x7f,0xf0,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x1f,0xc0,0xff,0x01,0xf8,0xff,0xff,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x0f,0x80,0x0f,0xfc,0x87,0xff,0xf1,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x07,0x00,0xe1,0xff,0x7f,0x3c,0xc0,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x07,0x00,0xfc,0xff,0xff,0x1b,0x00,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0x00,0xff,0xff,0xff,0x07,0x00,0xfe,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0x80,0xff,0xff,0xff,0x0f,0x00,0xfe,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0x80,0xff,0xff,0xff,0x3f,0x00,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0xc0,0xff,0xff,0xff,0x7f,0x00,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0xe0,0xff,0xff,0xff,0x7f,0x00,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0xf0,0xff,0xff,0xff,0xff,0x00,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0xf0,0xff,0xe7,0xe7,0xff,0x00,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x03,0xf8,0xff,0xe3,0xaf,0xff,0x01,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x07,0xfc,0xff,0xe1,0x3b,0xff,0x01,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x0f,0xfc,0xbf,0xe7,0xfd,0xfe,0x03,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x0f,0xfe,0x1f,0xe0,0xff,0xfd,0x03,0xfe,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x1f,0xfe,0x0f,0xf0,0x87,0xff,0x07,0xfe,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x3f,0xfe,0x07,0xf8,0x13,0xfc,0x07,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,0xfe,0x7f,0xfc,0xc7,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x7f,0xff,0xff,0xff,0xdf,0xff,0xef,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xef,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xbf,0xff,0xff,0xff,0xff,0xff,0xef,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xbf,0xff,0xff,0xff,0xff,0xff,0xef,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xbf,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xf7,0xff,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xe3,0xfe,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0x0f,0xfc,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xef,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xef,0xff,0xff,0xff,0xff,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xef,0xff,0x3f,0xe0,0xff,0xff,0xdf,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xef,0xff,0x3f,0x42,0xfa,0xff,0x9f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xe7,0xff,0x7f,0xff,0xcf,0xff,0x9f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xe7,0xff,0x7f,0xfe,0xef,0xff,0x9f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xc7,0xff,0xff,0x00,0xf0,0xff,0x9f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xc7,0xff,0xff,0x01,0xf8,0xff,0x9f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0xc1,0xff,0xff,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0x1f,0xff,0xff,0xff,0xff,0x80,0xff,0xff,0xff,0xff,0xff,0x1f,0xfe,0xff,0xff,0x1f,0xff,0xff,0xff,0x7f,0x00,0xff,0xff,0xff,0xff,0xff,0x0f,0xfc,0xff,0xff,0x1f,0xff,0xff,0xff,0x3f,0x00,0xff,0xff,0xff,0xff,0xff,0x0f,0xf8,0xff,0xff,0x1f,0xff,0xff,0xff,0x1f,0x00,0xfe,0xff,0xff,0xff,0xff,0x07,0xf0,0xff,0x81,0x1f,0xff,0xff,0xff,0x1f,0x00,0xf8,0xff,0xff,0xff,0xff,0x03,0xf0,0xff,0x01,0x1f,0x1f,0xf0,0xff,0x0f,0x00,0xf0,0xff,0xff,0xff,0xff,0x01,0xe0,0x7f,0x00,0x1f,0x0f,0x00,0xff,0x07,0x00,0xc0,0xff,0xff,0xff,0x7f,0x00,0xc0,0x3f,0x00,0x1f,0x7f,0x00,0xfe,0x07,0x00,0x80,0xff,0xff,0xff,0x1f,0x00,0x80,0x0f,0x00,0x1c,0x1f,0x00,0xf8,0x03,0x00,0x00,0xfe,0xff,0xff,0x03,0x00,0x00,0x03,0x00,0x18,0x07,0x00,0xe0,0x03,0x00,0x00,0xe0,0xff,0x7f,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x01,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x1c,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfe,0x1f,0x1f,0x78,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0x1f,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xff,0x1f,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xff,0x1f,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0xff,0x1f,0xff,0xff,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0xff,0x1f,0xff,0xff,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0xff,0x1f,0xff,0xff,0x1f,0x80,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0xf0,0xff,0x1f,0xff,0xff,0x3f,0xf0,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x1e,0xf8,0xff,0x1f,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x1f}; 
//const unsigned char col[] U8X8_PROGMEM = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x3f,0x00,0xfe,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf0,0x7f,0xf0,0x03,0x78,0x00,0x0e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf8,0xff,0x1e,0x00,0x80,0xc3,0x3f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf8,0xff,0x03,0x00,0x00,0xe4,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0xff,0x00,0x00,0x00,0xf8,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x7f,0x00,0x00,0x00,0xf0,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x7f,0x00,0x00,0x00,0xc0,0xff,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x3f,0x00,0x00,0x00,0x80,0xff,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x1f,0x00,0x00,0x00,0x80,0xff,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x0f,0x00,0x00,0x00,0x00,0xff,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x0f,0x00,0x18,0x18,0x00,0xff,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc,0x07,0x00,0x1c,0x50,0x00,0xfe,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf8,0x03,0x00,0x1e,0xc4,0x00,0xfe,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf0,0x03,0x40,0x18,0x02,0x01,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf0,0x01,0xe0,0x1f,0x00,0x02,0xfc,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0x01,0xf0,0x0f,0x78,0x00,0xf8,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0x01,0xf8,0x07,0xec,0x03,0xf8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x01,0x80,0x03,0x38,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x08,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x1c,0x01,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0xf0,0x03,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0xc0,0x1f,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0xc0,0xbd,0x05,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0x80,0x00,0x30,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x00,0x80,0x01,0x10,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x00,0xff,0x0f,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x00,0xfe,0x07,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00,0x00,0x00,0x00,0xe0,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xff,0x00,0x00,0x00,0x00,0x00,0xf0,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0xc0,0xff,0x00,0x00,0x00,0x00,0x00,0xf0,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0xe0,0xff,0x01,0x00,0x00,0x00,0x00,0xf8,0x0f,0x00,0x7e,0x00,0x00,0x00,0x00,0xe0,0xff,0x07,0x00,0x00,0x00,0x00,0xfc,0x0f,0x00,0xfe,0x00,0xe0,0x0f,0x00,0xf0,0xff,0x0f,0x00,0x00,0x00,0x00,0xfe,0x1f,0x80,0xff,0x00,0xf0,0xff,0x00,0xf8,0xff,0x3f,0x00,0x00,0x00,0x80,0xff,0x3f,0xc0,0xff,0x00,0x80,0xff,0x01,0xf8,0xff,0x7f,0x00,0x00,0x00,0xe0,0xff,0x7f,0xf0,0xff,0x03,0xe0,0xff,0x07,0xfc,0xff,0xff,0x01,0x00,0x00,0xfc,0xff,0xff,0xfc,0xff,0x07,0xf8,0xff,0x1f,0xfc,0xff,0xff,0x1f,0x00,0x80,0xff,0xff,0xff,0xff,0xff,0x0f,0xfe,0xff,0xff,0xfe,0xff,0xff,0xff,0xc1,0xff,0xff,0xff,0xff,0xff,0xff,0x0f,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0f,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0f,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0f,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x07,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xf3,0x03,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x01,0x00,0xe0,0x87,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x7f,0x00,0x00,0x00,0x00,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3f,0x00,0x00,0x00,0x00,0xf8,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x3f,0x00,0x00,0x00,0x00,0xf0,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x1f,0x00,0x00,0x00,0x00,0xe0,0x7f,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xfb,0x0f,0x00,0x00,0x00,0x00,0xc0,0x0f,0xfc,0xff,0xff,0xff,0xff,0xff,0xff,0xe1,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; 
void vDisplayDht11Data(HalDht11Data_t *HalDht11Data)
{
  
  U8G2_ClearBuffer();
  
#ifdef LANGUAGE_CHINESE
    
  char str[3];
  uint8 x,y,w,box_y;
  U8G2_SetFont(CHINESE_FONT);
  U8G2_DrawFrame(0, 0, U8G2_GetDisplayWidth(), U8G2_GetDisplayHeight());
  U8G2_SetFontMode(1);
  U8G2_SetDrawColor(DISPLAY_MODE);
  
  y = 16;
  box_y = y+4;
  U8G2_DrawBox(0, 0, U8G2_GetDisplayWidth(), box_y);
  
  U8G2_SetDrawColor(!DISPLAY_MODE);

  w = U8G2_GetGlyphWidth(u16FindUnicode(CHINESE_MAX_WIDTH));
  x = (U8G2_GetDisplayWidth()/2-w*2) / 2 ;
  vDrawGBK(x, y, MENU_STR_TEMP);
  //U8G2_DrawStr( U8G2_GetDisplayWidth()/2 - U8G2_GetGlyphWidth(u16FindUnicode("|"))/2+2 , y, "|");
  U8G2_DrawVLine(U8G2_GetDisplayWidth()/2, 0,   box_y);
  U8G2_DrawVLine(U8G2_GetDisplayWidth()/2-1, 0, box_y);
  
  x +=  U8G2_GetDisplayWidth()/2 ;
  vDrawGBK(x, y, MENU_STR_HUMI);
  
#else
  char str[3];
  uint8 x,y,box_y;
  U8G2_SetFont(TITLE_FONT);
  U8G2_DrawFrame(0, 0, U8G2_GetDisplayWidth(), U8G2_GetDisplayHeight());
  U8G2_SetFontMode(1);
  U8G2_SetDrawColor(DISPLAY_MODE);
  
  x = (U8G2_GetDisplayWidth()/2-U8G2_GetStrWidth("TEMP")) / 2;
  y = U8G2_GetMaxCharHeight() + 3;
  box_y = y + 4;
  U8G2_DrawBox(0, 0, U8G2_GetDisplayWidth(), box_y);
  
  U8G2_SetDrawColor(!DISPLAY_MODE);
  U8G2_DrawStr(x, y , "TEMP");
  
  //U8G2_DrawStr(U8G2_GetDisplayWidth()/2 -U8G2_GetStrWidth("|")/2, y, "|");
  U8G2_DrawVLine(U8G2_GetDisplayWidth()/2, 0,   box_y);
  U8G2_DrawVLine(U8G2_GetDisplayWidth()/2-1, 0, box_y);
  
  x +=  U8G2_GetDisplayWidth()/2;
  U8G2_DrawStr(x, y, "HUMI");
  
#endif
#if (defined DISPLAY_MODE ) && (DISPLAY_MODE == FALSE)  
    U8G2_DrawBox(0, box_y, U8G2_GetDisplayWidth(), U8G2_GetDisplayHeight()- box_y );
#endif   
  U8G2_SetFont(//u8g2_font_fub42_tn
               //u8g2_font_logisoso38_tn
               //u8g2_font_fur42_tn
               //u8g2_font_inr38_tn
               //u8g2_font_osb41_tn
               //u8g2_font_inb42_mn
               u8g2_font_inb30_mn
                //u8g2_font_temp_humi_7x13
                 );
  U8G2_SetDrawColor(DISPLAY_MODE);
  str[0] = HalDht11Data->u8Buff[2] / 10 +'0';
  str[1] = HalDht11Data->u8Buff[2] % 10 +'0';
  str[2] = '\0';
  U8G2_DrawStr((U8G2_GetDisplayWidth()/2 - U8G2_GetStrWidth(str))/2, 58, str);
  str[0] = HalDht11Data->u8Buff[0] / 10 +'0';
  str[1] = HalDht11Data->u8Buff[0] % 10 +'0';
  str[2] = '\0';
  
  
  U8G2_DrawStr((U8G2_GetDisplayWidth()/2 - U8G2_GetStrWidth(str))/2 +64, 58, str);
  vDrawInterfaceFramwork();
  U8G2_SendBuffer();
  printf("T&H %d %d\n", HalDht11Data->u8Buff[2], HalDht11Data->u8Buff[0]);
  
  zclTemperatureSensor_MeasuredValue = HalDht11Data->u8Buff[2];
  zclHumiditySensor_MeasuredValue = HalDht11Data->u8Buff[0];
  

  vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
              TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
              ZCL_CLUSTER_ID_MS_TEMPERATURE_MEASUREMENT,
              ATTRID_MS_TEMPERATURE_MEASURED_VALUE);

  vReportAtrr(TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT, 
              TEMPERATURE_HUMIDITY_SENSOR_ENDPOINT,
              ZCL_CLUSTER_ID_MS_RELATIVE_HUMIDITY,
              ATTRID_MS_PRESSURE_MEASUREMENT_MEASURED_VALUE);

  vSendWriteToServer_Bind(BIND_CLUSTER, BIND_ATTRIBUTE);

}

/*******************************************************************************  
 * Function:  TemHumiControlBindDevicesTtrategy()
 * Description:   TemHumiControlBindDevicesTtrategy
 * Input parameter:   int16 tempUp, int16 tempDown, uint16 humiUp, uint16 humiDown
 * Return parameter:   void 
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void TemHumiControlBindDevicesTtrategy(int16 tempUp, int16 tempDown, uint16 humiUp, uint16 humiDown)
{        
   if(zclTemperatureSensor_MeasuredValue > tempUp)
   {
      zcl_FanMode_e8 = FAN_MODE_MEDIUM;
   }
   else if(zclTemperatureSensor_MeasuredValue < tempDown)
   {
      zcl_FanMode_e8 = FAN_MODE_MEDIUM;
   }

   if(zclHumiditySensor_MeasuredValue > humiUp)
   {}
   else if(zclHumiditySensor_MeasuredValue < humiDown)
   {}
}
void zclTemperatureHumiditySensor_ProcessZDOMsgs(zdoIncomingMsg_t *inMsg )
{
  //ZStatus_t ZStatus;
  ZDO_ActiveEndpointRsp_t *EndpointRsp = NULL;
  zAddrType_t dstAddr;
  
  ZDO_NwkIEEEAddrResp_t *IEEEAddrRsp = NULL;

      
  switch( inMsg->clusterID )
  {
    case NWK_addr_rsp:
      
      break;
      
    case Match_Desc_rsp:
      {
        
        EndpointRsp = ZDO_ParseEPListRsp( inMsg );
        
        printf("Match_Desc_rsp\n");
        dstAddr.addr.shortAddr = EndpointRsp->nwkAddr;
        dstAddr.addrMode = Addr16Bit;
        if(NULL  != bindFindExisting(zclTemperatureHumiditySensor_SimpleDesc.EndPoint, &dstAddr, EndpointRsp->epList[0]))
        {  
           u8BindInfoTableNvRead();
           osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, MATCH_BIND_EVT, MATCH_BIND_EVT_DELAY);
           osal_mem_free ( EndpointRsp );
           break;
        }
        if(EndpointRsp->nwkAddr == NLME_GetCoordShortAddr())
        {
          addBindInfo(EndpointRsp->epList[0], EndpointRsp->nwkAddr);
          APSME_LookupExtAddr(EndpointRsp->nwkAddr, &dstAddr.addr.extAddr[0]);
          bSetBindInfoExtAddr(EndpointRsp->nwkAddr, &dstAddr.addr.extAddr[0]);
          osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, MATCH_BIND_EVT, MATCH_BIND_EVT_DELAY);
          u8BindInfoTableNvWrite();
        }
        else{
         
        addBindInfo(EndpointRsp->epList[0], EndpointRsp->nwkAddr);
        ZDP_IEEEAddrReq( EndpointRsp->nwkAddr, 0, 0, 0 );
        printf("S i3e request\n");
        }
        osal_mem_free ( EndpointRsp );
      }
      break;
    case IEEE_addr_rsp:
     
      IEEEAddrRsp = ZDO_ParseAddrRsp( inMsg );
      printf("%x ieee_rsp\n", IEEEAddrRsp->nwkAddr);
      if(findBindInfo_nwkAddr(IEEEAddrRsp->nwkAddr))
      {
        //dstAddr.addrMode = Addr16Bit;
        //dstAddr.addr.shortAddr = IEEEAddrRsp->nwkAddr;
        dstAddr.addrMode = Addr64Bit;
        osal_memcpy(&dstAddr.addr.extAddr[0] , &IEEEAddrRsp->extAddr[0], Z_EXTADDR_LEN);
      
        if(NULL  == bindFindExisting(zclTemperatureHumiditySensor_SimpleDesc.EndPoint, &dstAddr, findBindInfoEp(IEEEAddrRsp->nwkAddr)))
        {
          bSetBindInfoExtAddr(IEEEAddrRsp->nwkAddr, &dstAddr.addr.extAddr[0]);
          u8BindInfoTableNvWrite();
        }
        else
        {
          u8BindInfoTableNvRead();
        }
         osal_start_timerEx(zclTemperatureHumiditySensor_TaskID, MATCH_BIND_EVT, MATCH_BIND_EVT_DELAY);
      }
      osal_mem_free ( IEEEAddrRsp );
      break;
      
    default:
      break;
  }
}

void vAppSendMatchDescReqBroadcast(uint16 clusterID)
{
   zAddrType_t addr;
   afStatus_t afStatus; 
   addr.addrMode = Addr16Bit;
   addr.addr.shortAddr = NWK_BROADCAST_SHORTADDR;

   if ( ZDO_AnyClusterMatches( 1, &clusterID, zclTemperatureHumiditySensor_SimpleDesc.AppNumOutClusters,
                             zclTemperatureHumiditySensor_SimpleDesc.pAppOutClusterList ) )
  {
    // Try to match with a device in the allow bind mode
    afStatus = ZDP_MatchDescReq( &addr, NWK_BROADCAST_SHORTADDR,
                           zclTemperatureHumiditySensor_SimpleDesc.AppProfId, 1, &clusterID, 0, (cId_t *)NULL, 0 );
    printf("1 Match afStatus %x\n", afStatus);
  }
  else if ( ZDO_AnyClusterMatches( 1, &clusterID, zclTemperatureHumiditySensor_SimpleDesc.AppNumInClusters,
                                  zclTemperatureHumiditySensor_SimpleDesc.pAppInClusterList ) )
  {
    afStatus = ZDP_MatchDescReq( &addr, NWK_BROADCAST_SHORTADDR,
                           zclTemperatureHumiditySensor_SimpleDesc.AppProfId, 0, (cId_t *)NULL, 1, &clusterID, 0 );
    
    printf("2 Match afStatus %x\n", afStatus);
  }
 
}

/*******************************************************************************  
 * Function:   vSendWriteToServer_Bind(uint16 Cluster, uint16 u16Attr)
 * Description:   uint16 Cluster
 * Input parameter:   uint16 Cluster
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void vSendWriteToServer_Bind(uint16 u16Cluster, uint16 u16Attr)
{
    uint8 y=0;
    zclAttrRecsList *pRec = zclFindAttrRecsList( zclTemperatureHumiditySensor_SimpleDesc.EndPoint );
    zclWriteCmd_t *writeCmd;
    afAddrType_t dstAddr;
    //ZStatus_t ZStatus; 

    writeCmd = osal_mem_alloc( sizeof( zclWriteCmd_t ) + (1 * sizeof( zclWriteRec_t )) );
    writeCmd->numAttr = 1;
    writeCmd->attrList[0].attrID = u16Attr;
    
    if ( (pRec != NULL) && (writeCmd != NULL))
    {
         for( y = 0; y < pRec->numAttributes; y++)
         {
            if((pRec->attrs[y].clusterID == u16Cluster) && (pRec->attrs[y].attr.attrId == u16Attr))
            {  
              writeCmd->attrList[0].dataType = pRec->attrs[y].attr.dataType;
              writeCmd->attrList[0].attrData = (uint8 *)pRec->attrs[y].attr.dataPtr;
              break;
            }
         }
     
     dstAddr.addrMode = (afAddrMode_t)AddrNotPresent;
     dstAddr.panId = _NIB.nwkPanId;

     //ZStatus =  
       zcl_SendWrite(zclTemperatureHumiditySensor_SimpleDesc.EndPoint, &dstAddr,u16Cluster, writeCmd,
                              ZCL_FRAME_CLIENT_SERVER_DIR, FALSE, bdb_getZCLFrameCounter());

     //printf("Sw s %x\n", ZStatus);
    } 
    if ( writeCmd != NULL)
      osal_mem_free(writeCmd);
}

/*******************************************************************************  
 * Function:   vSendReadToServer_Bind(uint16 Cluster, uint16 u16Attr)
 * Description:   uint16 Cluster
 * Input parameter:   uint16 Cluster
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void vSendReadToServer_Bind(uint16 u16Cluster, uint16 u16Attr)
{
    zclReadCmd_t *zclReadCmd;
    afAddrType_t dstAddr;
    //ZStatus_t ZStatus; 
    
    zclReadCmd = osal_mem_alloc( sizeof( zclReadCmd_t ) + (1 * sizeof( uint16 )) );
    
    if( zclReadCmd != NULL)
    {
      zclReadCmd->numAttr = 1;
      zclReadCmd->attrID[0] = u16Attr;
      
   
       dstAddr.addrMode = (afAddrMode_t)AddrNotPresent;
       dstAddr.panId = _NIB.nwkPanId;

       //ZStatus =  
         zcl_SendRead(zclTemperatureHumiditySensor_SimpleDesc.EndPoint, &dstAddr,u16Cluster, zclReadCmd,
                                ZCL_FRAME_CLIENT_SERVER_DIR, FALSE, bdb_getZCLFrameCounter());

       //printf("Sw s %x\n", ZStatus);

       osal_mem_free(zclReadCmd);
    }
}
/*******************************************************************************  
 * Function:   vSendWriteToServer(uint16 u16Cluster, uint16 u16Attr, uint16 u16Addr)
 * Description:   uint16 Cluster
 * Input parameter:   uint16 Cluster
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void vSendWriteToServer(uint16 u16Cluster, uint16 u16Attr, uint16 u16Addr)
{
    uint8 y=0;
    zclAttrRecsList *pRec = zclFindAttrRecsList( zclTemperatureHumiditySensor_SimpleDesc.EndPoint );
    zclWriteCmd_t *writeCmd;
    afAddrType_t dstAddr;
    ZStatus_t ZStatus; 
    writeCmd = osal_mem_alloc( sizeof( zclWriteCmd_t ) + (1 * sizeof( zclWriteRec_t )) );
    writeCmd->numAttr = 1;
    writeCmd->attrList[0].attrID = u16Attr;
    
    if ( (pRec != NULL) && (writeCmd != NULL))
    {
         for( y = 0; y < pRec->numAttributes; y++)
         {
            if((pRec->attrs[y].clusterID == u16Cluster) && (pRec->attrs[y].attr.attrId == u16Attr))
            {  
              writeCmd->attrList[0].dataType = pRec->attrs[y].attr.dataType;
              writeCmd->attrList[0].attrData = (uint8 *)pRec->attrs[y].attr.dataPtr;
              break;
            }
         }
     
     dstAddr.addrMode = (afAddrMode_t)Addr16Bit;
     dstAddr.addr.shortAddr = u16Addr;
     dstAddr.panId = _NIB.nwkPanId;
     dstAddr.endPoint = zclTemperatureHumiditySensor_SimpleDesc.EndPoint;
     
     ZStatus =  zcl_SendWrite(zclTemperatureHumiditySensor_SimpleDesc.EndPoint, &dstAddr,u16Cluster, writeCmd,
                              ZCL_FRAME_CLIENT_SERVER_DIR, FALSE, bdb_getZCLFrameCounter());

    printf("Sw s %x\n", ZStatus);
    } 
    if ( writeCmd != NULL)
      osal_mem_free(writeCmd);
}
/*******************************************************************************  
 * Function:   addBindInfo(uint8 dstEp, uint16 nwkAddr)
 * Description:   delete BindInfo[0], add the new one to BindInfo[large]
 * Input parameter:   uint8 dstEp, uint16 nwkAddr
 * Return parameter:   void
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void addBindInfo(uint8 dstEp, uint16 nwkAddr)
{            
   
   if(findBindInfo(dstEp, nwkAddr)==FALSE)
   {
     for(uint8 i =0; i < BIND_INFO_CNT; i++)
     {
        BindInfoTable.BindInfo[i] = BindInfoTable.BindInfo[i+1];
     }
     BindInfoTable.BindInfo[BIND_INFO_CNT- 1].endpoint = dstEp;
     BindInfoTable.BindInfo[BIND_INFO_CNT- 1].nwkAddr = nwkAddr;  
     //printf("i %d, add Ep %d, addr %x\n",  BIND_INFO_CNT- 1, BindInfo[BIND_INFO_CNT -1 ].endpoint,  BindInfo[BIND_INFO_CNT -1].nwkAddr);
   }
}
/*******************************************************************************  
 * Function:   findBindInfo(uint8 dstEp, uint16 nwkAddr)
 * Description:   find exist BindInfo
 * Input parameter:   uint8 dstEp, uint16 nwkAddr
 * Return parameter:   bool
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
bool findBindInfo(uint8 dstEp, uint16 nwkAddr)
{          
   for(uint8 i =0; i<BIND_INFO_CNT; i++)
   {
      if(BindInfoTable.BindInfo[i].endpoint == dstEp && BindInfoTable.BindInfo[i].nwkAddr ==  nwkAddr)
      {
        //printf("find i %d, Ep %d, addr %x\n", i, BindInfo[i].endpoint, BindInfo[i].nwkAddr);
        return TRUE;
      }
   }
  return FALSE;         
}


/*******************************************************************************  
 * Function:  getBindInfo(uint8 dstEp, uint16 nwkAddr)
 * Description:   get exist BindInfo
 * Input parameter:   uint8 dstEp, uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
BindInfo_t *getBindInfo(uint8 dstEp, uint16 nwkAddr)
{            
   
   for(uint8 i =0; i < BIND_INFO_CNT; i++)
   {
      if(BindInfoTable.BindInfo[i].endpoint == dstEp && BindInfoTable.BindInfo[i].nwkAddr ==  nwkAddr)
        return (& BindInfoTable.BindInfo[i]);
   }
  return (BindInfo_t *)NULL;         
}
/*******************************************************************************  
 * Function:  getBindInfoWithAddr( uint16 nwkAddr)
 * Description:   get exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
BindInfo_t *getBindInfoWithAddr( uint16 nwkAddr)
{           
   for(uint8 i =0; i<BIND_INFO_CNT; i++)
   {
      if(BindInfoTable.BindInfo[i].nwkAddr == nwkAddr)
        return (&BindInfoTable.BindInfo[i]);
   }
  return (BindInfo_t *)NULL;         
}


/*******************************************************************************  
 * Function:  initBindInfoTable()
 * Description:   initBindInfoTable
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void initBindInfoTable(void)
{           
   
   osal_memset(&BindInfoTable.BindInfo, 0xff , sizeof(BindInfoTable.BindInfo));  
   BindInfoTable.cnt =0;
   
}
/*******************************************************************************  
 * Function:  deleteBindInfo()
 * Description:   get exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
bool checkBindInfoIsNull(void)
{           
   if(BindInfoTable.BindInfo[BIND_INFO_CNT-1].nwkAddr < NWK_ADDR_MAXIMUM)
     return TRUE;
   
   return FALSE;
}

/*******************************************************************************  
 * Function:  bSetBindInfoExtAddr( uint16 nwkAddr, uint8 *extAddr)
 * Description:   get exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
bool bSetBindInfoExtAddr( uint16 nwkAddr, uint8 *extAddr)
{           
   for(uint8 i =0; i<BIND_INFO_CNT; i++)
   {
      if(osal_memcmp(extAddr, &BindInfoTable.BindInfo[i].extAddr[0], Z_EXTADDR_LEN))
      {
         BindInfoTable.BindInfo[i].nwkAddr = nwkAddr;
         return TRUE;
      }
      else if(BindInfoTable.BindInfo[i].nwkAddr == nwkAddr )
      {
        
        if(BindInfoTable.cnt < BIND_INFO_CNT)
          BindInfoTable.cnt++;
        
        osal_memcpy(&BindInfoTable.BindInfo[i].extAddr[0], extAddr, Z_EXTADDR_LEN); 
        
        return TRUE;
      }
   }
  return FALSE;         
}
       
/*******************************************************************************  
 * Function:   findBindInfo_nwkAddr(uint16 nwkAddr)
 * Description:   find exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   bool
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
bool findBindInfo_nwkAddr( uint16 nwkAddr)
{          
   for(uint8 i =0; i<BIND_INFO_CNT; i++)
   {
      if( BindInfoTable.BindInfo[i].nwkAddr ==  nwkAddr)
      {
        //printf("find i %d, Ep %d, addr %x\n", i, BindInfo[i].endpoint, BindInfo[i].nwkAddr);
        return TRUE;
      }
   }
  return FALSE;         
}

/*******************************************************************************  
 * Function:   findBindInfoEp(uint16 nwkAddr)
 * Description:   find exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   bool
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
uint8 findBindInfoEp( uint16 nwkAddr)
{          
   for(uint8 i =0; i<BIND_INFO_CNT; i++)
   {
      if( BindInfoTable.BindInfo[i].nwkAddr ==  nwkAddr)
      {
        //printf("find i %d, Ep %d, addr %x\n", i, BindInfo[i].endpoint, BindInfo[i].nwkAddr);
        return BindInfoTable.BindInfo[i].endpoint;
      }
   }
  return 0xFF;         
}

/*******************************************************************************  
 * Function:   checkExtAddrValid(uint8 const *extAddr)
 * Description:   find exist BindInfo
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   bool
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
uint8 checkExtAddrValid(uint8 const *extAddr)
{          
   uint8 cnt = 0;
   uint8 addr[Z_EXTADDR_LEN];
   
   osal_memcpy(addr, extAddr, Z_EXTADDR_LEN);
   
   for(uint8 i =0; i<Z_EXTADDR_LEN; i++)
   {
      if(0xFF == addr[i] || 0x00 == addr[i])
      {
          cnt++;
      }
   }
  if(cnt == Z_EXTADDR_LEN)
   return FALSE;     
   
   return TRUE;
}
/*******************************************************************************  
 * Function:   u8InitBindInfoTableNv(
 * Description:   
 * Input parameter:   void
 * Return parameter:   u8
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
uint8 u8InitBindInfoTableNv( void)
{    
  uint8 status = 0;
  status = osal_nv_item_init(ZCD_NV_BIND_INFO, sizeof(BindInfoTable), &BindInfoTable);
  printf("nv i %d\n", status);
  return status;
}
/*******************************************************************************  
 * Function:   u8BindInfoTableNvRead
 * Description:  
 * Input parameter:   void
 * Return parameter:   u8
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
uint8 u8BindInfoTableNvRead( void)
{          
  uint8 status = 0;
  status = osal_nv_read(ZCD_NV_BIND_INFO, 0, sizeof(BindInfoTable), &BindInfoTable);
  printf("nv r %d, size %d\n", status, sizeof(BindInfoTable));
  return status;
}
/*******************************************************************************  
 * Function:   u8BindInfoTableNvWrite
 * Description:  
 * Input parameter:   void
 * Return parameter:   u8
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
uint8 u8BindInfoTableNvWrite( void)
{        
  uint8 status = 0;
  status = osal_nv_write(ZCD_NV_BIND_INFO, 0, sizeof(BindInfoTable), &BindInfoTable);
  printf("nv w %d\n", status);
  return status; 
}
/*******************************************************************************  
 * Function:  deleteBindInfoNv()
 * Description:   deleteBindInfoNv
 * Input parameter:   uint16 nwkAddr
 * Return parameter:   BindInfo_t *
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void deleteBindInfoNv(void)
{        
   initBindInfoTable();
   u8BindInfoTableNvWrite();
}
/*******************************************************************************  
 * Function:  SetPollRateInPowerSavingMode()
 * Description:   SetPollRateInPowerSavingMode
 * Input parameter:  
 * Return parameter:   
 * Author: Newbit_Msming      
 * Date@@2018/5/10    
 * Other:  
*******************************************************************************/ 
void SetPollRateInPowerSavingMode(void)
{
#ifdef POWER_SAVING
 
  if(Dev_NwkState ==  DEV_END_DEVICE)
  {
     printf("Pan %04X, F %04X, Addr %04X\n", _NIB.nwkPanId, _NIB.nwkCoordAddress, _NIB.nwkDevAddress);
//     NwkPollReq(0);
//     NLME_SetPollRate(0);
     
  }
//  else if(Dev_NwkState == DEV_NWK_JOINING \
//        ||Dev_NwkState == DEV_NWK_SEC_REJOIN_CURR_CHANNEL\
//        ||Dev_NwkState == DEV_NWK_ORPHAN\
//        ||Dev_NwkState == DEV_NWK_BACKOFF\
//        ||Dev_NwkState == DEV_NWK_SEC_REJOIN_ALL_CHANNEL\
//        ||Dev_NwkState == DEV_NWK_TC_REJOIN_CURR_CHANNEL\
//        ||Dev_NwkState == DEV_NWK_TC_REJOIN_ALL_CHANNEL\
//         )
//  {
//     printf("Rejoin rate %lu\n", REJOIN_POLL_RATE);
//     NLME_SetPollRate(REJOIN_POLL_RATE);
//  }
//  else
//  {
//    printf("poll rate %lu\n", POLL_RATE);
//    NLME_SetPollRate(POLL_RATE);
//  }
#endif
}
/*******************************************************************************
*******************************************************************************/


